package com.hds.modules.app.service.impl;


import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hds.modules.app.dao.UserDao;
import com.hds.common.exception.RRException;
import com.hds.common.validator.Assert;
import com.hds.modules.app.entity.UserEntity;
import com.hds.modules.app.enums.UserEnum;
import com.hds.modules.app.form.LoginForm;
import com.hds.modules.app.service.UserService;
import com.hds.modules.sys.dao.base.SysMemberShipDao;
import com.hds.modules.sys.entity.base.SysMemberShipEntity;
import com.hds.modules.sys.service.base.SysMemberShipService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private SysMemberShipDao sysMemberShipDao;

	@Override
	public UserEntity queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setMobile(mobile);
		return userDao.selectOne(userEntity);
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		//Assert.isNull(user, "手机号或密码错误");
		Integer level = UserEnum.VipLevel.TOURIST.getLevel();
		SysMemberShipEntity memberShip = sysMemberShipDao.queryByLevel(level);

		if(user==null){
			UserEntity userEntity=new UserEntity();
			userEntity.setCreateTime(new Date());
			userEntity.setLatestLoginTime(new Date());
			userEntity.setMobile(form.getMobile());
			if(memberShip!=null)userEntity.setLevelId(memberShip.getId());
			Integer rst = userDao.insert(userEntity);

			return userEntity.getUserId();
		}else{
			UserEntity userEntity=new UserEntity();
			userEntity.setUserId(user.getUserId());
			userEntity.setLatestLoginTime(new Date());
			userDao.updateById(userEntity);
			return user.getUserId();
		}

		//密码错误
		// if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getCaptcha()))){
		//	throw new RRException("手机验证码错误");
		// }
		//return user.getUserId();
	}
}
